package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.network.UnauthorizedException
import com.fishingwithme.android.utils.EventBus
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
open class BaseViewModel @Inject constructor(
    private val preferencesManager: PreferencesManager
) : ViewModel() {
    
    /**
     * Handle exceptions that may occur in repository calls
     * Specifically handles UnauthorizedException by clearing user data
     */
    protected fun handleException(e: Exception): Exception {
        return when (e) {
            is UnauthorizedException -> {
                // Clear user data when unauthorized
                viewModelScope.launch {
                    preferencesManager.clearAccessToken()
                    preferencesManager.clearLoginUser()
                }
                // Notify observers that an unauthorized error occurred
                EventBus.postUnauthorizedEvent()
                e
            }
            else -> e
        }
    }
}